<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>画板聊天室</title>
</head>
    <div id="tableCanvas" style="float: left;"></div>

    <div style="float: left; padding-left: 20px;">
        <div id="colorCanvas"></div>
        <a href="javascript:clear()">清空</a><br>
        <a href="javascript:changeSlide()">切换连贯画笔</a><br>
        <a href="javascript:changeSpray()">切换喷射模式</a>
    </div>

    <div style="width: 380px; height: 500px; float: left; padding-left: 20px;">
        <div style="position: relative; border: 1px solid #F0F0F0; width: 100%; height: 100%; padding: 10px;">
            <div style="width: calc(100% - 20px); height: calc(100% - 70px); position: absolute; border: 1px solid #F0F0F0; overflow-y:auto;">
                <ul id="chatMsgContent" style="padding-inline-start: 10px;">
                </ul>
            </div>
            <div style="width: 100%; height: 50px; position: absolute; bottom: 0px;">
                <textarea id="chatMsgText" style="width: 80%; vertical-align: bottom;" maxlength="1000"></textarea>
                <input type="button" value="发送" style="vertical-align: bottom;" onclick="sendChatMsgText()">
            </div>
        </div>
    </div>
<body>
</body>
<script src="/js/jquery-3.2.1.min.js"></script>
<script src="/js/color_select.js"></script>
<script src="/js/web_socket_utils.js"></script>
<script>
    // 创建画布
    const canvas = document.createElement('canvas');
    canvas.width = 901;
    canvas.height = 601;
    document.getElementById("tableCanvas").appendChild(canvas);
    const ctx = canvas.getContext('2d');
    var isSlide = false;

    // 定义网格尺寸
    const gridSize = 10; // 这里设定网格大小为 10x10

    // 绘制网格
    function drawGrid() {
        for (let x = 0; x <= canvas.width; x += gridSize) {
            ctx.moveTo(Math.floor(x) + 0.5, 0);
            ctx.lineTo(Math.floor(x) + 0.5, canvas.height);
        }
        for (let y = 0; y <= canvas.height; y += gridSize) {
            ctx.moveTo(0, Math.floor(y) + 0.5);
            ctx.lineTo(canvas.width, Math.floor(y) + 0.5);
        }

        ctx.strokeStyle = "rgba(128, 128, 128, 1)"; // 设定网格线颜色
        ctx.lineWidth = 0.5; // 设置线条粗细为1像素
        ctx.stroke();
    }

    // 初始化所有单元格颜色为黑色
    function initializeCells() {
        const columns = Math.floor(canvas.width / gridSize);
        const rows = Math.floor(canvas.height / gridSize);
        for (let x = 0; x < columns; x++) {
            for (let y = 0; y < rows; y++) {
                markCell(x, y, 'rgb(255, 255, 255)');
            }
        }
    }

    // 标记特定颜色
    function markCell(x, y, color) {
        ctx.fillStyle = color;
        ctx.fillRect(x * gridSize + 1, y * gridSize + 1, gridSize - 1, gridSize - 1);
    }

    // 添加点击事件
    canvas.addEventListener('click', function(event) {
        const rect = canvas.getBoundingClientRect();
        const x = Math.floor((event.clientX - rect.left) / gridSize);
        const y = Math.floor((event.clientY - rect.top) / gridSize);
        console.log(`x：${x}，y：${y}`)
        handleCellClick(event);
    });

    var isMouseDown = false;
    canvas.addEventListener('mousedown', function(e) {
        isMouseDown = true;
    });
    canvas.addEventListener('mouseup', function() {
        isMouseDown = false;
    });
    var lastX = -1;
    var lastY = -1;
    // 添加移动事件
    canvas.addEventListener('mousemove', function(event) {
        if (isMouseDown && isSlide) {
            const rect = canvas.getBoundingClientRect();
            const x = Math.floor((event.clientX - rect.left) / gridSize);
            const y = Math.floor((event.clientY - rect.top) / gridSize);
            if (x !== lastX || y !== lastY) {
                handleCellClick(event);
                lastX = x;
                lastY = y;
            }
        }
    });

    // 点击事件执行逻辑
    function handleCellClick(event) {
        const rect = canvas.getBoundingClientRect();
        const x = Math.floor((event.clientX - rect.left) / gridSize);
        const y = Math.floor((event.clientY - rect.top) / gridSize);
        const pixelData = ctx.getImageData(x * gridSize + 1, y * gridSize + 1, 1, 1).data;
        if (x >= 0 && x < canvas.width / gridSize && y >= 0 && y < canvas.height / gridSize) {
            if (pixelData[0] === 255 && pixelData[1] === 255 && pixelData[2] === 255) {
                markCell(x, y, COLOR_SELECTOR.value);
                WEB_SOCKET_UTILS.send(`table:${x},${y}#${COLOR_SELECTOR.value}`);
            } else {
                markCell(x, y, "rgb(255, 255, 255)");
                WEB_SOCKET_UTILS.send(`table:${x},${y}#rgb(255, 255, 255)`);
            }
        }
    }

    // 改变颜色
    function changeColor(x, y, color) {
        if (x >= 0 && x < canvas.width / gridSize && y >= 0 && y < canvas.height / gridSize) {
            markCell(x, y, color);
        }
    }

    // 获取初始化消息
    function initTableMessage() {
        $.ajax({
            url: '/init/table',
            type: 'GET',
            async: false,
            success: function (data) {
                if (data && data.length > 0) {
                    let msgs = data.split("|");
                    for (let i = 0; i < msgs.length; i++) {
                        let info = msgs[i].split("#");
                        changeColor(info[0].split(",")[0], info[0].split(",")[1], info[1]);
                    }
                }
            }
        })
    }

    // 获取初始化消息
    function initChatMessage() {
        $.ajax({
            url: '/init/chat',
            type: 'GET',
            async: false,
            success: function (data) {
                if (data && data.length > 0) {
                    let msgs = data.split("※※");
                    for (let i = 0; i < msgs.length; i++) {
                        let info = msgs[i].split("※");
                        addChatMsgText(info[0], info[1])
                    }
                }
            }
        })
    }

    drawGrid();
    initializeCells();
    initChatMessage();

    // 初始化颜色选择器
    COLOR_SELECTOR.init("colorCanvas");

    // 初始化消息内容
    initTableMessage();

    // 初始化消息
    WEB_SOCKET_UTILS.initWebSocket(`ws://${window.location.hostname}/websocket/`);
    WEB_SOCKET_UTILS.message = (evt) => {
        if (evt.data && evt.data && evt.data.startsWith("table:")) {
            let msg = evt.data.substring("table:".length);
            let infos = msg.split("|");
            for (let i = 0; i < infos.length; i++) {
                let info = infos[i].split("#");
                changeColor(info[0].split(",")[0], info[0].split(",")[1], info[1]);
            }
        } else if (evt.data && evt.data && evt.data === 'tableClear') {
            location.reload();
        } else if (evt.data && evt.data && evt.data.startsWith("chat:")) {
            let msg = evt.data.substring("chat:".length);
            let info = msg.split("※");
            addChatMsgText(info[0], info[1])
        }
    }

    function clear() {
        var userInput = prompt("请输入清空密码：", "");
        if (userInput !== null) {
            $.ajax({
                url: '/init/table/clear?pwd=' + userInput,
                type: 'POST',
                async: false,
                success: function (data) {
                    if (data === 'OK') {
                        alert('清空成功！');
                        location.reload();
                    } else {
                        alert('密码错误！');
                    }
                }
            })
        }
    }

    function changeSpray() {
        // var userInput = prompt("请输入清空密码：", "");
        $.ajax({
            url: '/init/chat/changeSpray?userId=' + WEB_SOCKET_UTILS.userId,
            type: 'POST',
            success: function (data) {
                console.log(data);
            }
        })
    }

    function changeSlide() {
        isSlide = !isSlide;
    }

    function addChatMsgText(userId, msg) {
        let newMessage = document.createElement('li');
        newMessage.style.listStyle = 'none';
        newMessage.style.marginBottom = '10px';
        newMessage.innerHTML = `<span style="color: cornflowerblue;">${userId}：</span><span>${msg}</span>`;
        let chatContent = document.getElementById("chatMsgContent");
        chatContent.appendChild(newMessage);
        // 滚动到最底部
        chatContent.parentNode.scrollTop = chatContent.parentNode.scrollHeight;
    }

    function sendChatMsgText() {
        if (document.getElementById("chatMsgText").value == null || document.getElementById("chatMsgText").value == '') {
            return;
        }
        addChatMsgText(WEB_SOCKET_UTILS.userId, document.getElementById("chatMsgText").value)
        WEB_SOCKET_UTILS.send(`chat:${WEB_SOCKET_UTILS.userId}※${document.getElementById("chatMsgText").value}`);
        document.getElementById("chatMsgText").value = '';
    }

</script>
</html>